<?php defined('SYSPATH') or die('No direct script access.');

/*
*
*
*
*/

class Controller_Checkpurchaseorder extends Controller_Admin
{
    public function before()
    {
        try{
            ACL::Required('checkpurchaseorder_index');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        include_once(MODPATH.'/common/logs.php');
        include_once(MODPATH.'/commonapi/classes/purchaseApi.php');
        parent::before();
    }
    /**
     *  退货审批列表
     *  作者:kelvin
     * */
    public function Action_index(){
        $this->title = __("供应商退货审批");
        $where = 'WHERE 1 ';
        if(isset($_GET['create_user_id']) && !empty($_GET['create_user_id'])){
            $where .= ' AND create_user_id = '.trim($_GET['create_user_id']);
        }
        if(isset($_GET['supplier_name']) && !empty($_GET['supplier_name'])){
            $where .= ' AND supplier_name LIKE \'%'.trim($_GET['supplier_name']).'%\'';
        }
        if(isset($_GET['sku']) && !empty($_GET['sku'])){
            $where .= ' AND sku = \''.trim($_GET['sku']).'\'';
        }
        if(isset($_GET['select_store']) && !empty($_GET['select_store'])){
            $where .= ' AND warehouseid = \''.trim($_GET['select_store']).'\'';
        }
        if(isset($_GET['enterprise_dominant']) && !empty($_GET['enterprise_dominant'])){
            $where .= ' AND enterprise_dominant = \''.trim($_GET['enterprise_dominant']).'\'';
        }
        if(isset($_GET['status']) && !empty($_GET['status'])){
            $where .= ' AND status = \''.trim($_GET['status']).'\'';
        }
        if(isset($_GET['date_from']) && !empty($_GET['date_from'])){
            $where .= ' AND create_time >= \''.trim($_GET['date_from']).'\'';
        }
        if(isset($_GET['date_to']) && !empty($_GET['date_to'])){
            $where .= ' AND create_time <= \''.trim($_GET['date_to']).'\'';
        }
        $sql = 'SELECT * from supplier_returns_approval '.$where;
        $view        = View::factory('purchase/checkpurchaseorder');
        $result = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
        $pagination = Pagination::factory(array(
            'items_per_page' => 5,
            'total_items' => count($result),
            'uri' => $this->request->uri(),
        ));
        $where .= "ORDER BY id desc";
        if(!isset($_GET['down'])||!$_GET['down']){
            $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
            $where .= "  LIMIT " . (($current_page - 1) * 5) . ",5";
        }
        $sql = 'SELECT * from supplier_returns_approval '.$where;
        $result = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
//        echo "<pre>";print_r(DB::query(Database::SELECT, $sql)->compile('newerp'));echo "</pre>";die;
        $status = array(
            '10'=>'发起申请',
            '20'=>'审核通过',
            '30'=>'审核驳回',
//            '40'=>'财务审核通过',
//            '50'=>'财务审核驳回',
            '60'=>'仓库审核通过',
            '70'=>'仓库审核驳回',
            '80'=>'仓库发货',
            '90'=>'已关闭',
        );
        if(isset($_GET['down'])&&$_GET['down']){
            $this->action_downCsv($result);die;
        }
//        foreach ($result as $v){
//            Inventory::query_sku_inventory($v['sku'],$v['supplier_id']);
//        }
        $view->set('result',$result);
        $view->set('status',$status);
        $view->set("pagination", $pagination);
        $view->set('enterprise_dominant',Kohana::$config->load('enterprise_dominant')->as_array());
        $view->set("warehouses",Kohana::$config->load('vmi_warehouse')->as_array());
        $this->response->body($view);
    }
    /**
     *  供应商退货申请
     *  作者:kelvin
     * */
    public function action_returnApplication()
    {
        $this->title = __("供应商退货申请");
        $where = '';
        if(isset($_GET['supplier_name']) && !empty($_GET['supplier_name'])){
            $where .= ' AND b.supplier_name like \'%'.trim($_GET['supplier_name']).'%\'';
        }
        if(isset($_GET['sku']) && !empty($_GET['sku'])){
            $where .= ' AND a.sku = \''.trim($_GET['sku']).'\'';
        }
        if(isset($_GET['store']) && !empty($_GET['store'])){
            $where .= ' AND a.warehouseid = \''.trim($_GET['store']).'\'';
        }
        if(isset($_GET['enterprise_dominant']) && !empty($_GET['enterprise_dominant'])){
            $where .= ' AND a.enterprise_dominant = \''.trim($_GET['enterprise_dominant']).'\'';
        }
        $date = date('Y-m-d');
        $stocks = array();
        $sql = "select a.sku,a.supplier_id,warehouseid,enterprise_dominant,sum(`quantity`) as qty,
            b.supplier_name,b.productname
             from (
            SELECT `sku`, `stock` `quantity`,warehouseid,enterprise_dominant,supplier_id
                    FROM `sku_stocks`
                    WHERE  `date`='$date'
                    AND `stock` <>0
                    UNION ALL
                    SELECT `sku`, `warehouse_quantity` `quantity`,warehouseid,enterprise_dominant,supplier_id
                    FROM `warehouseorders`
                    WHERE `warehouse_date`>='$date'
                    UNION ALL
                    SELECT `sku`, -`quantity` `quantity`,warehouseid,enterprise_dominant,supplier_id
                    FROM `deliveryorders`
                    WHERE `delivery_date`>='$date'
            ) a 
            LEFT JOIN vmi_supplier_skus b ON b.sku = a.sku AND b.supplier_id = a.supplier_id
            WHERE b.isavailable = 1 $where
            GROUP BY a.`sku`,a.warehouseid,a.enterprise_dominant,a.supplier_id ";
//        $sql = 'SELECT a.sku,warehouseid,stock sku_qty,b.supplier_id,a.enterprise_dominant,b.supplier_name,b.productname from sku_stocks a,vmi_supplier_skus b
//            WHERE a.sku=b.sku
//            '.$where;
        $result = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();

        $pagination = Pagination::factory(array(
            'items_per_page' => 5,
            'total_items' => count($result),
            'uri' => $this->request->uri(),
        ));
        $limit = '' ;
        if(!isset($_GET['down'])||!$_GET['down']){
            $current_page = isset($_GET['page']) ? $_GET['page'] : 1;
            $limit = " LIMIT " . (($current_page - 1) * 5) . ",5";
        }
        $sql = $sql .$limit;
        $result = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
//        echo "<pre>";print_r($result);echo "</pre>";die;
        if(isset($_GET['down'])&&$_GET['down']){
            $this->action_downCsv($result);die;
        }
        $view        = View::factory('purchase/returnApplication');
        $view->set('result',$result);
        $view->set("pagination", $pagination);
        $view->set('warehouses',Kohana::$config->load('vmi_warehouse')->as_array());
        $view->set('enterprise_dominant',Kohana::$config->load('enterprise_dominant')->as_array());
        $this->response->body($view);
    }
    /**
     *  单个申请提交
     *  作者:kelvin
     * */
    public function action_saveOne()
    {
        $data = $_POST['arr'];
        $data['status'] = 10;
        $data['create_time'] = date('Y-m-d H:i:s');;
        $data['create_user_id'] = User::active_user()->id;
        if((int)$data['return_qty']<=0) {
            echo '提交失败，退货量输入有误';die;
        }
        if((int)$data['return_qty']>(int)Inventory::query_sku_inventory($data['sku'],$data['supplier_id'],$data['warehouseid'],$data['enterprise_dominant'])){
            echo '提交失败，退货量大于库存量';die;
        }
        list($id,)= DB::insert('supplier_returns_approval',array_keys($data))->values(array_values($data))->execute('newerp');
        $sql = DB::insert('supplier_returns_approval',array_keys($data))->values(array_values($data))->compile('newerp');
        if($id){
            logs::write_log($id,'supplier_returns_approval/insert',1,$sql);
            echo '提交成功';die;
        }else{
            logs::write_log($id,'supplier_returns_approval/insert',0,$sql);
            echo '提交失败';die;
        }
    }
    /**
     *  批量申请提交
     *  作者:kelvin
     * */
    public function action_saveAll()
    {
//        $data = $_POST['arr'];
//        echo '<pre>';print_r($_POST['arr']);echo '</pre>';die;
        $msg = '';
        $flag = 0;
        $list = $_POST['arr'];
        foreach ($list as &$data){
            $data['status'] = 10;
            $data['create_time'] = date('Y-m-d H:i:s');;
            $data['create_user_id'] = User::active_user()->id;
            if((int)$data['return_qty']<=0) {
                $msg .= $data['sku'].'退货量输入有误<br>';continue;
            }
            if((int)$data['return_qty']>(int)Inventory::query_sku_inventory($data['sku'],$data['supplier_id'],$data['warehouseid'],$data['enterprise_dominant'])){
                $msg .=  $data['sku'].'退货量大于库存量<br>';continue;
            }
        }
        if($msg!=''){
            echo $msg;die;
        }else{
            if(count($list)>=1){
                foreach ($list as $key =>$val){
                    list($id,) = DB::insert('supplier_returns_approval',array_keys($val))->values(array_values($val))->execute('newerp');
                    $sql = DB::insert('supplier_returns_approval',array_keys($val))->values(array_values($val))->compile('newerp');
                    if(!$id){
                        logs::write_log($id,'supplier_returns_approval/insert',0,$sql);
                        $flag +=1;
                    }else{
                        logs::write_log($id,'supplier_returns_approval/insert',1,$sql);
                    }
                }
                if($flag==0){
                    echo '操作成功';die;
                }else{
                    echo '操作失败';
                }
            }
        }


    }
    /*
     * 审核退货
     */
    public function action_checkStatus() {
        if(isset($_GET['id'])) {
            $id = (array)$_GET['id'];
            $id = array_map('intval', $id);
            $rows = DB::select('sku','return_qty','supplier_id','warehouseid','enterprise_dominant','status')
                ->from('supplier_returns_approval')->where('id','in',$id)->execute('newerp')->as_array();
            foreach($rows as $row) {
                if(($row['status'] > 10) && ($_GET['checked'] != '-1')) {
                    echo "操作失败，{$row['sku']}已审核";die;
                }
                if($row['return_qty']>Inventory::query_sku_inventory($row['sku'],$row['supplier_id'],$row['warehouseid'],$row['enterprise_dominant'])){
                    echo "操作失败,{$row['sku']}退货量大于库存量";die;
                }
            }
            $user_id = User::active_user()->id;
            $now_time = date('Y-m-d H:i:s');
            $status = ($_GET['checked'] == '1') ? 20 : ($_GET['checked'] == '-1' ? 90 : 30);
            $sql = "UPDATE supplier_returns_approval SET status={$status},supplychain_user_id='{$user_id}',supplychain_time='{$now_time}'"
                . " WHERE id IN (" . implode(",", $id) . ")";
            // echo $sql;exit;
            if(DB::query(Database::UPDATE, $sql)->execute('newerp')){
                logs::write_log(implode(",", $id),'supplier_returns_approval/update',1,$sql);
                echo '操作成功';
            }else{
                logs::write_log(implode(",", $id),'supplier_returns_approval/update',0,$sql);
                echo '操作失败';
            }
            exit;
        }
        echo '参数有错';
    }
    /**
     * 批量审核
     */
    public function action_checkBatch() {
        if(isset($_GET['id'])) {
            $now_time = date('Y-m-d H:i:s');
            $user_id = User::active_user()->id;
            if($_GET['status'] == 10){
                $set = ',`supplychain_user_id` = '.$user_id.',`supplychain_time` = \''.$now_time.'\'';
            }else if ($_GET['status'] == 20){
                $set = ',`warehouse_user_id` = '.$user_id.',`warehouse_time` = \''.$now_time.'\'';
//                $set = ',`finance_user_id` = '.$user_id.',`finance_time` = \''.$now_time.'\'';
            }else{
                echo '操作失败，状态不一致';die;
//                $set = ',`warehouse_user_id` = '.$user_id.',`warehouse_time` = \''.$now_time.'\'';
            }
            $statusList = DB::select('status')->from('supplier_returns_approval')->where('id','in',$_GET['id'])->group_by('status')->execute('newerp')->as_array();
            if(count($statusList)>1){
                echo '操作失败，状态不一致';die;
            }
            $status = $_GET['status']+$_GET['type'];
            $msg = '';
            if(in_array($status,array(20,40,60))){
                $skuList = DB::select('sku','return_qty','supplier_id','warehouseid','enterprise_dominant','status')->from('supplier_returns_approval')->where('id','in',$_GET['id'])->execute('newerp')->as_array();
                foreach ($skuList as $sku){
                    if($sku['return_qty']>Inventory::query_sku_inventory($sku['sku'],$sku['supplier_id'],$sku['warehouseid'],$sku['enterprise_dominant'])){
                        $msg .= $sku['sku']."退货量大于库存量<br>";
                    }
                }
            }
            if($msg !=''){
                echo $msg;die;
            }else{
                $sql = "UPDATE `supplier_returns_approval` SET `status` = ".$status.$set." WHERE `id` in (".implode(',',$_GET['id']).")";
                if($status==80){
                    foreach ($_GET['id'] as $v){
                        $this->action_deliveryForReturnId($v);
                    }

                }
                if(DB::query(Database::UPDATE, $sql)->execute('newerp')){
                    logs::write_log($_GET['id'],'supplier_returns_approval/update',1,$sql);
                    echo '操作成功';
                }else{
                    logs::write_log($_GET['id'],'supplier_returns_approval/update',0,$sql);
                    echo '操作失败';
                }
            }
            exit;

        }
        echo '参数有错';
    }
    /**
     * 导出
     */
    public function action_downCsv($data)
    {
        if(count($data)>0){
            set_time_limit(0);
            ini_set('memory_limit','2048M');
            $ware = Kohana::$config->load('vmi_warehouse')->as_array();
            $enter = Kohana::$config->load('enterprise_dominant')->as_array();
            $output = fopen('php://output', 'w') or die("can't open php://output");
            header("Content-Type: application/csv");
            header("Content-Disposition: attachment; filename=供应商退货审批导出.(" .date("Ymd").").csv");
            ob_end_clean();
            $firstLine = array(
                'supplier_name' =>'供应商',
                'sku' =>'sku',
                'sku_name' =>'中文名称',
                'warehouseid' =>'仓库',
                'enterprise_dominant' =>'主体',
                'create_user_id' =>'提交人',
                'create_time' =>'提交时间',
                'quantity' =>'库存量',
                'return_qty' =>'退货量',
                'status' =>'审批状态',
                'remark' =>'备注'
            );
            $status = array(
                '10'=>'发起申请',
                '20'=>'供应链审核通过',
                '30'=>'供应链审核驳回',
//                '40'=>'财务审核通过',
//                '50'=>'财务审核驳回',
                '60'=>'仓库审核通过',
                '70'=>'仓库审核驳回',
                '80'=>'仓库发货',
                '90'=>'供应商确认收货',
            );
            fputcsv($output, array_values($firstLine));
            foreach ($data as &$_data) {
                $_data['quantity'] = Inventory::query_sku_inventory($_data['sku'],$_data['supplier_id'],$_data['warehouseid'],$_data['enterprise_dominant']);
                $_data['enterprise_dominant'] = $enter[$_data['enterprise_dominant']];
                $_data['warehouseid'] = $ware[$_data['warehouseid']];
                $_data['status'] = $status[$_data['status']];
                $_data['create_user_id'] = Erpuser::nick_by_id($_data['create_user_id']);
                $_output = array();
                foreach ($firstLine as $key => $val) {
                    $_output[$key] = $_data[$key];
                }
                fputcsv($output, array_values($_output));
            }

            fclose($output) or die("can't close php://output");
            exit;
        }else{
            echo "<script>alert('数据为空');history.go(-1)</script>";die;
        }
    }

    public function action_deliveryForReturnId($id)
    {
        $result = DB::select('*')->from('supplier_returns_approval')->where('id','=',$id)->execute('newerp')->current();
        if($result){
            $skuList = DB::select('*')->from('vmi_supplier_skus')->where('sku','=',$result['sku'])->execute('newerp')->current();
            $data = array(
                'warehouseid' =>$result['warehouseid'],
                'delivery_date' =>date('Y-m-d H:i:s'),
                'delivery_man'=>$result['sku'],
                'sku'=>$result['sku'],
                'sku_name'=>$result['sku_name'],
                'op_time'=>date('Y-m-d H:i:s'),
                'order_id'=>0,
                'sku_standard'=>$skuList['size'],
                'storage_position'=>'',
                'quantity'=>$result['return_qty'],
                'remark'=>'供应商退货审批出库',
                'enterprise_dominant'=>$result['enterprise_dominant'],
                'supplier_id'=>$result['supplier_id'],
                'type'=>70
            );
            $common = new Service_common();
            $price = $common->get_sku_price($data['sku']);
            $userid = User::active_user()->id;
            $log_sql =  DB::insert('deliveryorders',
                array('delivery_date','warehouseid','op_time','order_id','delivery_department','delivery_man','sku',
                    'sku_name','sku_standard','storage_position','quantity','single_price','money','cost','remark',
                    'type','supplier_id','enterprise_dominant'))
                ->values(array($data['delivery_date'],$data['warehouseid'],$data['op_time'],$data['order_id'],
                    0,$userid,$data['sku'],$data['sku_name'],$data['sku_standard'], $data['storage_position'],
                    $data['quantity'],0,0,$price*$data['quantity'],$data['remark'],$data['type'],
                    $data['supplier_id'],$data['enterprise_dominant']))
                ->compile('newerp');
            list($insert_id, $total_rows) = DB::insert('deliveryorders',
                array('delivery_date','warehouseid','op_time','order_id','delivery_department','delivery_man','sku',
                    'sku_name','sku_standard','storage_position','quantity','single_price','money','cost','remark',
                    'type','supplier_id','enterprise_dominant'))
                ->values(array($data['delivery_date'],$data['warehouseid'],$data['op_time'],$data['order_id'],
                    0,$userid,$data['sku'],$data['sku_name'],$data['sku_standard'], $data['storage_position'],
                    $data['quantity'],0,0,$price*$data['quantity'],$data['remark'],$data['type'],
                    $data['supplier_id'],$data['enterprise_dominant']))
                ->execute('newerp');
            if($insert_id){
                logs::write_log($insert_id,'deliveryorders/insert',1,$log_sql);
                return true;
            }else{
                logs::write_log($insert_id, 'deliveryorders/insert',0,$log_sql, '特殊出库单创建失败！');
                return false;
            }
        } else{
            return false;
        }
    }
    /**
     *  退供应商发货确认页面
     *  作者:kelvin
     * */
    public function action_returnShow()
    {
        $view = View::factory('purchase/returnShow');
        $supplier = supplierskus::getSupplierAddress($_GET['id']);
        $data = DB::select('*')->from('supplier_returns_approval')->where('id','=',intval($_GET['id']))->execute('newerp')->as_array();
        if($data[0]['status'] == 70 ||$data[0]['status']==80){
            $supplier = json_decode($data[0]['logistics_json'],true);
        }
//        echo "<pre>";print_r($supplier);echo "</pre>";die;
        $view->set('data',$data?$data[0]:array());
        $view->set('supplier',$supplier);
        $view->set('link',$_GET['link']);
        echo $view->render();die;
    }
    /**
     *  退供应商发货确认保存
     *  作者:kelvin
     * */
    public function action_returnShowSave()
    {
        if($_POST && is_array($_POST['logistics'])){
            $statusList = DB::select('*')->from('supplier_returns_approval')->where('id','=',$_POST['id'])->group_by('status')->execute('newerp')->current();
            if($statusList['return_qty']>Inventory::query_sku_inventory($statusList['sku'],$statusList['supplier_id'],$statusList['warehouseid'],$statusList['enterprise_dominant'])){
                $msg = $statusList['sku']."退货量大于库存量";
                echo "<script>alert('$msg');history.go(-1);</script>";die;
            }
            if($statusList['status']==20){
                $user_id = User::active_user()->id;
                $set = ',`ship_user_id` = '.$user_id.',`ship_time` = \''.date('Y-m-d H:i:s').'\'';
                //推送分销直上
                //执行出库
                if(!$this->action_deliveryForReturnId($_POST['id'])){
                    echo "<script>alert('出库失败');history.go(-1);</script>";die;
                }
                $sql = "UPDATE `supplier_returns_approval` SET `status` = 80,logistics_json = '".addslashes(json_encode($_POST['logistics']))."'".$set." WHERE `id` = ".$_POST['id'];
                if(DB::query(Database::UPDATE, $sql)->execute('newerp')!=false){
                    $api = PurchaseApi::supplierReturnsPull($_POST['id']);
                    if($api['state']==200){
                        DB::update('supplier_returns_approval')->set('is_pull','=','1')->where('id','=',$_POST['id'])->execute('newerp');
                    }
                    logs::write_log($_POST['id'],'supplier_returns_approval/update',1,$sql);
                    echo "<script>alert('操作成功');location.href='".URL::site()."checkpurchaseorder/index';</script>";die;
                }else{
                    logs::write_log($_POST['id'],'supplier_returns_approval/update',0,$sql);
                    echo "<script>alert('操作失败');history.go(-1);</script>";die;
                }
            }else{
                echo "<script>alert('状态不一致，请刷新后操作');location.href='".URL::site()."checkpurchaseorder/index';</script>";die;
            }
        }
    }
    /**
     *  重新推送退货通知到分销直上
     *  作者:kelvin
     * */
    public function action_pull()
    {
        $api = PurchaseApi::supplierReturnsPull($_GET['id']);
        if($api['code']==200){
            $pull = "UPDATE `supplier_returns_approval` SET `is_pull`= 1 WHERE `id`= " . $_GET['id'] ;
            if(DB::query(Database::UPDATE, $pull)->execute('newerp')!=false){
                logs::write_log($_GET['id'],'supplier_returns_approval/update',1,$pull);
                echo '推送成功';die;
            }else{
                logs::write_log($_GET['id'],'supplier_returns_approval/update',0,$pull);
                echo '操作成功';die;
            }
        }else{
            $msg = '推送失败，可能的原因：<br>' . (isset($api['msg']) ? $api['msg'] : '接口响应失败');
            echo $msg;die;
        }
    }
}